package com.xfc.sde.service;

import com.xfc.sde.component.DataSourceContext;
import com.xfc.sde.dto.MultiRouteDataSource;
import com.xfc.sde.dto.OverlayDTO;
import com.xfc.sde.utils.JDBCUtil;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.*;

/**
 * @Author: chenss
 * @CreateTime: 2024-09-19
 * @Description: 叠加分析服务
 * @Version: 1.0
 */

@Service
public class OverlayService {

    @Autowired
    private MultiRouteDataSource multiDataSource; // 注入你的 MultiRouteDataSource

    @Autowired
    private JDBCUtil jdbcUtil;

    public Connection getConnection() {
        String dataSourceKey = DataSourceContext.getDataSource(); // 获取当前数据源的 key
        DataSource dataSource = multiDataSource.getDataSource(dataSourceKey); // 获取相应的数据源
        Connection conn = null;
        try {
            if (dataSource != null) {
                conn = dataSource.getConnection(); // 从数据源获取连接
            } else {
                throw new SQLException("No DataSource found for key: " + dataSourceKey);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    private MultiPolygon convertWktToMultiPolygon(String wkt) {
        WKTReader reader = new WKTReader();
        try {
            Geometry geometry = reader.read(wkt);
            if (geometry instanceof MultiPolygon) {
                return (MultiPolygon) geometry;
            } else if (geometry instanceof Polygon) {
                // 将 Polygon 转换为 MultiPolygon
                Polygon polygon = (Polygon) geometry;
                return new MultiPolygon(new Polygon[]{polygon}, polygon.getFactory());
            } else {
                throw new IllegalArgumentException("提供的 WKT 不是 Polygon 或 MultiPolygon 类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("WKT 转换失败: " + e.getMessage());
        }
    }
    public String overlayWithPostGIS(OverlayDTO overlayDTO) {
        // 从DTO中获取数据
        String wkt = overlayDTO.getWkt();
        String layerName = overlayDTO.getLayerName();

        DataSourceContext.setDataSource(overlayDTO.getDataSourceKey());
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        String intersectionWkt=null;

        try {
            connection = getConnection();

            // 构建用于交集分析的SQL
            String sql = "SELECT objectid, ST_AsText(ST_Intersection(ST_GeomFromText(?,4490), shape)) AS intersection " +
                    "FROM sde.\"" + layerName + "\" " +
                    "WHERE ST_Intersects(ST_GeomFromText(?,4490), shape)";

            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, wkt); // 设置WKT
            pstmt.setString(2, wkt); // 因为两个地方都需要WKT，所以设置两次

            resultSet = pstmt.executeQuery();

            while (resultSet.next()) {
                int objectId = resultSet.getInt("objectid");
                intersectionWkt= resultSet.getString("intersection");
                System.out.println("ObjectID: " + objectId + " - Intersection: " + intersectionWkt);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "叠加分析失败！";
        } finally {
            // 释放资源
            jdbcUtil.releaseResc(resultSet, pstmt, connection);
            DataSourceContext.clearDataSource();
        }
        return intersectionWkt;
    }


    public String overlay(OverlayDTO overlayDTO) {

        MultiPolygon multiPolygon = convertWktToMultiPolygon(overlayDTO.getWkt());
        // 设置数据源
        DataSourceContext.setDataSource(overlayDTO.getDataSourceKey());

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 获取数据库连接
            connection = getConnection();
            statement = connection.createStatement();

            // 构造 SQL 查询
            String sql = "SELECT objectid, ST_AsText(shape) AS wkt_shape FROM sde.\"" + overlayDTO.getLayerName() + "\"";
            resultSet = statement.executeQuery(sql);

            // 进行叠加分析
            while (resultSet.next()) {
                Geometry geomFromLayer = new WKTReader().read(resultSet.getString("wkt_shape"));

                // 检查是否相交
                if (multiPolygon.intersects(geomFromLayer)) {
                    System.out.println("几何体相交！");
                    Geometry intersection = multiPolygon.intersection(geomFromLayer);
                    System.out.println("相交区域的 WKT 表示: " + intersection.toText());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "叠加分析失败！";
        } finally {
            // 释放资源
            jdbcUtil.releaseResc(resultSet, statement, connection);
            // 清理数据源上下文
            DataSourceContext.clearDataSource();
        }
        return "叠加分析完成！";
    }



}



